import 'package:music_player/model/musci_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:grpc/grpc.dart';
import 'package:music_player/rpc/generated/protos/music.pbgrpc.dart';
import 'package:provider/provider.dart';
import 'package:music_player/enums/music_mode.dart' as mm;

class MusicRpcServer extends MusicRpcServiceBase{

  static late final Server _musicServer;

  static Future<void> start(BuildContext context) async{
    try {
      _musicServer = Server.create(services: [MusicRpcServer(context)]);
      await _musicServer.serve(port: 9999);
      debugPrint("服务端已启动:${_musicServer.port}");
    } catch (e) {
      debugPrint("启动服务端失败: $e");
    }
  }

  static Future<void> stop() async{
    await _musicServer.shutdown();
  }

  final BuildContext context;
  late final MusicModel musicModel;
  MusicRpcServer(this.context){
    musicModel = context.read<MusicModel>();
  }

  @override
  Future<Empty> musicMode(ServiceCall call, MusicMode request) {
    debugPrint("音乐模式${request.mode.name}");
    switch(request.mode){
      case Mode.loop:
        musicModel.musicMode = mm.MusicMode.singleLoop;
        break;
      case Mode.random:
        musicModel.musicMode = mm.MusicMode.randomPlay;
        break;
      case Mode.sequential:
        musicModel.musicMode = mm.MusicMode.sequentialPlay;
        break;
    }
    return Future.value(Empty());
  }

  @override
  Future<Empty> nextMusic(ServiceCall call, Empty request) {
    debugPrint("下一首音乐");
    musicModel.nextMusic(context);
    return Future.value(request);
  }

  @override
  Future<Empty> playMusic(ServiceCall call, Empty request) {
    debugPrint("播放音乐");
    musicModel.playMusic(context);
    return Future.value(request);
  }

  @override
  Future<Empty> previousMusic(ServiceCall call, Empty request) {
    debugPrint("上一首音乐");
    musicModel.previousMusic(context);
    return Future.value(request);
  }

  @override
  Future<Music> thisMusic(ServiceCall call, Empty request) {
    debugPrint("当前音乐");
    return Future.value(Music(title: musicModel.thisMusic.title));
  }

}